#!/usr/bin/env python
#coding=utf-8

import os
import paramiko
import ConfigParser
import logging

#logger = paramiko.util.logging.getLogger()
#logger.setLevel(logging.WARN)

#_root_dir = os.path.abspath(os.path.dirname(__file__))
#paramiko.util.log_to_file(os.path.join(_root_dir,"..","logs","ssh.log"))

def ssh_passwd(ip,port,username,passwd,cmd):
    """
    使用密码方式的ssh
    param
    cmd:执行命令，是list
    """
    try:  
        ssh = paramiko.SSHClient()
        
        #自动接收未知的key验证,就是ssh的时候提示输入yes/no的
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  
        ssh.connect(ip,port,username,passwd,timeout=5)
        
        if type(cmd) == str:
            stdin, stdout, stderr = ssh.exec_command(cmd) 
            out = stdout.readlines()  
            #屏幕输出  
            for o in out:  
                print o,
            print '\033[32;1m###############%s\tOK################\033[0m\n'%(ip)
            ssh.close()
            
            return
        
        for m in cmd:  
            stdin, stdout, stderr = ssh.exec_command(m)  
#           stdin.write("Y")   #简单交互，输入 ‘Y’   
            out = stdout.readlines()  
            #屏幕输出  
            for o in out:  
                print o,  
        print '\033[32;1m###############%s\tOK################\033[0m\n'%(ip)  
        ssh.close()  
    except :  
        print '\033[31;1m###############%s\tError################\033[0m\n'%(ip)
        
def ssh_key(ip,port,username,keyfile,cmd):
    """
    使用key方式的ssh,密钥必须使用openssh生成
    param
    cmd:执行命令，是list
    keyfile:私钥文件
    
    usage:ssh_key('192.168.2.204',22,'root','H:\\test\\id_dsa',['df -h','ls /'])
    windows ssh:http://sourceforge.net/projects/sshwindows/files/OpenSSH%20for%20Windows%20-%20Release/3.8p1-1%2020040709%20Build/setupssh381-20040709.zip/download
    """
    try:
        key = paramiko.DSSKey.from_private_key_file(keyfile)
        ssh = paramiko.SSHClient()  
        #自动接收未知的key验证,就是ssh的时候提示输入yes/no的
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  
        ssh.connect(ip,port,username,pkey=key,timeout=5)  
        
        if type(cmd) == str:
            stdin, stdout, stderr = ssh.exec_command(cmd) 
            out = stdout.readlines()  
            #屏幕输出  
            for o in out:  
                print o,
            print '\033[32;1m###############%s\tOK################\033[0m\n'%(ip)
            ssh.close()
            
            return
        
        for m in cmd:  
            stdin, stdout, stderr = ssh.exec_command(m)     
            out = stdout.readlines()  
            #屏幕输出  
            for o in out:  
                print o,  
        print '\033[32;1m###############%s\tOK################\033[0m\n'%(ip)
        ssh.close()  
    except :  
        print '\033[31;1m###############%s\tError################\033[0m\n'%(ip)
        
def doconfig(config,pgname):
    """
    解析数据
    """
    #保存项目，ip地址和执行命令
    action_content = []
    
    #执行对应的项目
    auth_type = config.get(pgname, "type")
    ipaddr = config.get(pgname, "ip")
    
    for ip in ipaddr.split(','):
        if ':' in ip:
            new_ipaddr = ip.split(':')[0]
            port = ip.split(':')[1]
        else:
            new_ipaddr = ip
            port = 22

        if "general" in auth_type:
            auth = auth_type.split('_')[1]
            action_content.append({'programname':pgname,
                                    'username':config.get(auth_type, "username"),
                                    'ip':new_ipaddr,
                                    'port':port,
                                    'cmd':eval(config.get(pgname, "cmd")),
                                    auth:config.get(auth_type, auth),
                                    'comment':config.get(pgname, "comment"),
                                    })
        else:
            action_content.append({'programname':pgname,
                                   'username':config.get(pgname, "username"),
                                   'ip':new_ipaddr,
                                   'port':port,
                                   'cmd':eval(config.get(pgname, "cmd")),
                                   auth_type:config.get(pgname, auth_type),
                                   'comment':config.get(pgname, "comment"),
                                   })
    return action_content    
        
def readconfig(config_file,pgname = None):
    """
    读取配置文件信息
    """
    
    #读取ini配置文件
    config = ConfigParser.ConfigParser()
    config.read(config_file)
    
    #执行执行某个项目
    if pgname is not None:
        return doconfig(config,pgname)
    
    #保存项目，ip地址和执行命令
    action_content = []
    
    #获取所有的项
    section = config.sections()
    
    #获取项目对应的服务器信息
    for s in section:

        if 'general' not in s:
            action_content = action_content + doconfig(config,s)

    return action_content